// Todo.jsx
import './todo.css'
import { useStore } from '../store/index.js'
import { useState } from 'react'
import { observer } from 'mobx-react-lite'

function Todo() {
  const store = useStore()
  const [inputValue, setInputValue] = useState('')
  
  const handleAdd = () => {
    if (inputValue.trim()) {
      store.todoStore.addTodo(inputValue)
      setInputValue('')
    }
  }

  const handleKeyDown = (e) => {
    if (e.key === 'Enter') handleAdd()
  }

  return (
    <section className="todoapp">
      <header className="header">
        <h1>todos</h1>
        <input
          className="new-todo"
          autoFocus
          placeholder="What needs to be done?"
          value={inputValue}
          onChange={e => setInputValue(e.target.value)}
          onKeyDown={handleKeyDown}
        />
      </header>
      <section className="main">
        <input
          id="toggle-all"
          className="toggle-all"
          type="checkbox"
          checked={store.todoStore.allCompleted}
          onChange={() => store.todoStore.toggleAll()}
        />
        <label htmlFor="toggle-all"></label>
        <ul className="todo-list">
          {store.todoStore.list.map(item => (
            <li key={item.id} className={`todo ${item.completed ? 'completed' : ''}`}>
              <div className="view">
                <input
                  className="toggle"
                  type="checkbox"
                  checked={item.completed}
                  onChange={() => store.todoStore.changeTodoCompleted(item.id)}
                />
                <label>{item.title}</label>
                <button
                  className="destroy"
                  onClick={() => store.todoStore.removeTodo(item.id)}
                ></button>
              </div>
            </li>
          ))}
        </ul>
      </section>
      <footer className="footer">
        <span className="todo-count">
          任务总数：{store.todoStore.total} 已完成：{store.todoStore.completedCount}
        </span>
      </footer>
    </section>
  )
}

export default observer(Todo)